//导入共享数据包
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'

Page({
    //共享数据相关配置
    options: {
        styleIsolation: 'shared'
    },
    
    behaviors: [storeBindingsBehavior],

    //引入需要的共享数据
    storeBindings: {
        store,
        fields: {
            token: 'token',
            userInfo: 'userInfo'
        },
        actions: {}
    },

    data: {
      historyList: [],       // 历史记录列表
      page: 1,              // 当前页码
      pageSize: 10,         // 每页数量
      hasMore: true,        // 是否有更多数据
      classOptions: [       // 害虫类型选项
        {id: '', name: '全部'},
        {id: '松毛虫', name: '松毛虫'},
        {id: '天牛', name: '天牛'},
        {id: '松材线虫', name: '松材线虫'},
        // 其他害虫类型...
      ],
      classIndex: 0,        // 当前选中的害虫类型索引
      dateFilter: '',       // 日期筛选条件
      clsFilter: '',        // 害虫类型筛选条件
      loading: false        // 防止重复加载
    },
    
    onLoad() {
      this.setData({
        dateFilter: this.formatDate(new Date())
      });
    },

    onShow() {
        this.loadHistory();
    },
    
    // 加载历史记录
    loadHistory() {
      if (this.data.loading) return;
      
      this.setData({ loading: true });
      const { page, pageSize, clsFilter } = this.data;
      
      wx.showLoading({ title: '加载中...' });
      
      wx.request({
        url: `http://localhost:8980/detect/history?userId=${store.userInfo.id}`,
        method: 'GET',
        header: {
          'content-type': 'application/json',
          authentication: store.token
        },
        success: (res) => {
          if (res.data.code === 1) {
            const newList = page === 1 ? res.data.data : [...this.data.historyList, ...res.data.data];
            this.setData({
              historyList: newList,
              hasMore: res.data.data.length >= pageSize
            });
          } else {
            wx.showToast({
              title: res.data.msg || '加载失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
          console.error(err);
        },
        complete: () => {
          wx.hideLoading();
          this.setData({ loading: false });
        }
      });
    },
    
    // 加载更多
    loadMore() {
      if (!this.data.hasMore || this.data.loading) return;
      
      this.setData({
        page: this.data.page + 1
      }, () => {
        this.loadHistory();
      });
    },
    
    // 害虫类型筛选
    onClassFilter(e) {
      const index = e.detail.value;
      const cls = this.data.classOptions[index].id;
      this.setData({
        classIndex: index,
        clsFilter: cls,
        page: 1
      }, () => {
        this.loadHistory();
      });
    },
    
    // 日期筛选
    onDateFilter(e) {
      this.setData({
        dateFilter: e.detail.value,
        page: 1
      }, () => {
        this.loadHistory();
      });
    },
    
    // 查看详情
    viewDetail(e) {
      const index = e.currentTarget.dataset.index;
      const item = this.data.historyList[index];
      wx.navigateTo({
        url: `/pages/history-detail/history-detail?imageUrl=${encodeURIComponent(item.imageUrl)}&cls=${encodeURIComponent(item.cls)}&conf=${item.conf}`
      });
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}`;
    },
    
    // 格式化时间显示 - 由于接口没有返回时间，这里使用当前时间代替
    formatTime() {
      const date = new Date();
      return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
    }
});